import {queryPayment, queryRevenue} from '../../services/history/history';

const R = require('ramda');
import Constants from '../../utils/Constants'

export default {
	namespace: 'history',
	state: {
		names: [],
		banks: [],
		accounts: [],
		receiveBanks: [],
		receiveAccounts: []
	},
	reducers: {
        /**
         * 刷新state
         * 
         * @param state
         */
		refreshState(state, { payload }) {
			return { ...state, ...payload };
		}
	},
	effects: {
        /**
         * 来账信息 auto_complete
         * 
         */
		*queryRevenue({ payload }, { call, put }) {
			const res = yield call(queryRevenue, { ...R.omit(['onSuccess', 'onFail'])(payload) });
			if (res && res.data.resultCode === "ok") {

				let [names, banks, accounts, receiveBanks, receiveAccounts] = [[], [], [], [], []];
				if (res.data.content) {
					res.data.content.map(item => {
						names.push(item.name);
						banks.push(item.bank);
						accounts.push(item.account);
						receiveBanks.push(item.receiveBank);
						receiveAccounts.push(item.receiveAccount);
					})
				}

				yield put({
					type: 'refreshState',
					payload: {
						names: Array.from(new Set(names)),
						banks: Array.from(new Set(banks)),
						accounts: Array.from(new Set(accounts)),
						receiveBanks: Array.from(new Set(receiveBanks)),
						receiveAccounts: Array.from(new Set(receiveAccounts))
					}
				});
			} else {
				if (payload.onFail) payload.onFail();
			}
		},

        /**
         * 付款信息 auto_complete
         * 
         */
		*queryPayment({ payload }, { call, put }) {
			const res = yield call(queryPayment, { ...R.omit(['onSuccess', 'onFail'])(payload) });
			if (res && res.data.resultCode === "ok") {

				let [banks, accounts, receiveBanks, receiveAccounts] = [[], [], [], [], []];
				if (res.data.content) {
					res.data.content.map(item => {
						banks.push(item.payBank);
						accounts.push(item.payAccount);
						receiveBanks.push(item.receiveBank);
						receiveAccounts.push(item.receiveAccount);
					})
				}

				yield put({
					type: 'refreshState',
					payload: {
						banks: Array.from(new Set(banks)),
						accounts: Array.from(new Set(accounts)),
						receiveBanks: Array.from(new Set(receiveBanks)),
						receiveAccounts: Array.from(new Set(receiveAccounts))
					}
				});
			} else {
				if (payload.onFail) payload.onFail();
			}
		},
	},
	subscriptions: {
        setup({ history, dispatch }) {
            return history.listen(({ pathname }) => {
                const menus = JSON.parse(sessionStorage.getItem(Constants.USER_MENU));
                if(menus && !menus.find(item=>item.includes(pathname)) && pathname != '/logout'){
                    document.location.href = "/notAuthorized"
                }
            });
        }
    }
};